package com.firexxx.common.errors;

import org.springframework.util.StringUtils;

/**
 * Created by mmxu6 on 2019-09-01.
 */
public interface BusinessError {
    String getCode();

    String getMessage();

    void setCode(String code);

    void setMessage(String message);

    ErrorType getErrorType();

    void setErrorType(ErrorType errorType);

    default BusinessError message(String message) {
        if (StringUtils.isEmpty(message)) {
            return this;
        }

        this.setMessage(message);
        return this;
    }

    default String getLoggerMessage() {
        return "[" + getCode() + "]: " + getMessage();
    }

    default BusinessException getThrow() {
        return new BusinessException(this);
    }

    default BusinessException getThrow(String message) {
        return new BusinessException(this.message(message));
    }

    default BusinessException getThrow(String message, String loggerMessage, Object... args) {
        return getThrow(this.message(message), String.format(loggerMessage, args));
    }

    default BusinessException getThrow(BusinessError error, String loggerMessage, Object... args) {
        return new BusinessException(error, String.format(loggerMessage, args));
    }

    default void doThrow() throws BusinessException {
        ifThrow(true);
    }

    default void doThrow(String message) throws BusinessException {
        ifThrow(true, message);
    }

    default void doThrow(String message, String loggerMessage) throws BusinessException {
        ifThrow(true, message, loggerMessage);
    }


    default void ifThrow(boolean condition) throws BusinessException {
        if (condition) {
            throw getThrow();
        }
    }

    default void ifThrow(boolean condition, String message) throws BusinessException {
        if (condition) {
            throw getThrow(message);
        }
    }

    default void ifThrow(boolean condition, String message, String loggerMessage) throws BusinessException {
        if (condition) {
            throw getThrow(message, loggerMessage);
        }
    }

    default void elseThrow(boolean condition) throws BusinessException {
        ifThrow(!condition);
    }


    default void elseThrow(boolean condition, String message) throws BusinessException {
        ifThrow(!condition, message);
    }


    default void elseThrow(boolean condition, String message, String loggerMessage) throws BusinessException {
        ifThrow(!condition, message, loggerMessage);
    }
}
